let results = [];
let default_displayUnit = ['all', 'sci', 'ccf', 'cssci', 'cscd', 'sci-base', 'sci-up', 'pku','thcpl'];

function start() {
    return new Promise(function(resolve, reject) {
        chrome.tabs.executeScript({ code: 'location.hostname'}, function(result) {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(result);
            }
        });
    });
}

window.addEventListener('DOMContentLoaded', function () {
    start().then(function (result){
       if (result[0]==='ieeexplore.ieee.org'){
           ieee.storage.push(sci.getRankingSpanEn)
           ieee.start()
           fetchHTML().then(function (html) {
               let data = fetchData(html);
               matchAll(data)
           }).catch(function (error) {
               console.error('获取HTML内容时发生错误：', error);
           });
           executeContentScript()
               .then(function(result) {
                   console.log(result);
               })
               .catch(function(error) {
                   console.error(error);
               });
       }
       if (result[0]==='dl.acm.org'){
           window.alert(1234)
       }
    })
    // 等待1秒钟后执行
});

function executeContentScript() {
    return new Promise(function(resolve, reject) {
        chrome.tabs.executeScript({ file: "content-scripts.js" }, function(result) {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(result);
            }
        });
    });
}

// 使用这个函数执行 content.js


//
// //
// 异步获取HTML内容的函数
function fetchHTML() {
    return new Promise(function (resolve, reject) {
        chrome.tabs.executeScript({
            code: 'document.body.innerHTML'
        }, function (results) {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(results[0]);
            }
        });
    });
}
function fetchData(html) {
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(html, 'text/html');
    var xpathResult = xmlDoc.evaluate('//xpl-results-item/div[1]/div[1]/div[2]/div/a', xmlDoc, null, XPathResult.ANY_TYPE, null);
    var textValues = [];
    // 遍历XPath结果
    var aElement = xpathResult.iterateNext();
    while (aElement) {
        // 获取<a>元素之间的文本内容
        var textContent = aElement.textContent.trim();
        // 存储文本内容
        textValues.push(textContent);
        // 获取下一个<a>元素
        aElement = xpathResult.iterateNext();
    }
    return textValues
}


/////////////////////////// 匹配

function calculateLevenshteinDistance(a, b) {
    if (a.length === 0) return b.length;
    if (b.length === 0) return a.length;

    const matrix = [];

    for (let i = 0; i <= b.length; i++) {
        matrix[i] = [i];
    }

    for (let j = 0; j <= a.length; j++) {
        matrix[0][j] = j;
    }

    for (let i = 1; i <= b.length; i++) {
        for (let j = 1; j <= a.length; j++) {
            if (b.charAt(i - 1) === a.charAt(j - 1)) {
                matrix[i][j] = matrix[i - 1][j - 1];
            } else {
                matrix[i][j] = Math.min(
                    matrix[i - 1][j - 1] + 1,
                    matrix[i][j - 1] + 1,
                    matrix[i - 1][j] + 1
                );
            }
        }
    }

    return matrix[b.length][a.length];
}

function fuzzyMatch(phrase1, phrase2, threshold) {
    const distance = calculateLevenshteinDistance(phrase1.toLowerCase(), phrase2.toLowerCase());
    const maxLength = Math.max(phrase1.length, phrase2.length);
    const similarityRatio = 1 - distance / maxLength;
    return similarityRatio >= threshold;
}

function findMatchingKeys(object, data, threshold) {
    try {
        data.forEach(target => {
            for (let key in object) {
                if (!fuzzyMatch(key, target, threshold)) {
                    results[target] = 0;
                }
                else{
                    results[target] = object[key];
                }
            }
        });
    } catch (err) {
        console.error("An error occurred during findMatchingKeys:", err);
        window.alert("An error occurred: " + err.message);
    }
}


function matchAll(data){
    let threshold = 0.70
    findMatchingKeys(rankingFullName, data, threshold);
}

// function render(object){
//     if (object===null){
//         return null;
//     }
//     else {
//         //     渲染步骤
//     }
// }




// 示例用法

